<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>逻辑时钟 - 读论文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

        <!-- MathJax -->
        <script async type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="chapter_1.html">读论文活动</a></li><li class="chapter-item expanded affix "><li class="part-title">6.824 分布式系统</li><li class="chapter-item expanded "><a href="Mapreduce.html"><strong aria-hidden="true">1.</strong> Mapreduce</a></li><li class="chapter-item expanded "><a href="GFS.html"><strong aria-hidden="true">2.</strong> GFS</a></li><li class="chapter-item expanded "><a href="VM-FT.html"><strong aria-hidden="true">3.</strong> VM-FT</a></li><li class="chapter-item expanded "><a href="Raft.html"><strong aria-hidden="true">4.</strong> Raft</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="Raft0.html"><strong aria-hidden="true">4.1.</strong> 感性认识Raft</a></li><li class="chapter-item expanded "><a href="Raft1.html"><strong aria-hidden="true">4.2.</strong> 什么是Raft？</a></li><li class="chapter-item expanded "><a href="Raft2.html"><strong aria-hidden="true">4.3.</strong> 复制状态机（Replicated State Machine）</a></li><li class="chapter-item expanded "><a href="Raft3.html"><strong aria-hidden="true">4.4.</strong> What's wrong with Paxos?</a></li><li class="chapter-item expanded "><a href="Raft4.html"><strong aria-hidden="true">4.5.</strong> 向可理解性进军</a></li><li class="chapter-item expanded "><a href="Raft5.html"><strong aria-hidden="true">4.6.</strong> Raft共识算法（零）</a></li><li class="chapter-item expanded "><a href="Raft6.html"><strong aria-hidden="true">4.7.</strong> Raft共识算法（一）——基础概念</a></li><li class="chapter-item expanded "><a href="Raft7.html"><strong aria-hidden="true">4.8.</strong> Raft共识算法（二）——选举leader</a></li><li class="chapter-item expanded "><a href="Raft8.html"><strong aria-hidden="true">4.9.</strong> Raft共识算法（三）——日志备份（log replication）</a></li><li class="chapter-item expanded "><a href="Raft9.html"><strong aria-hidden="true">4.10.</strong> Raft共识算法（四）——安全性和选举限制</a></li><li class="chapter-item expanded "><a href="Raft10.html"><strong aria-hidden="true">4.11.</strong> Raft共识算法（五）——如何提交之前term里的entry</a></li><li class="chapter-item expanded "><a href="Raft11.html"><strong aria-hidden="true">4.12.</strong> Raft共识算法（六）——安全性定理</a></li><li class="chapter-item expanded "><a href="Raft12.html"><strong aria-hidden="true">4.13.</strong> Raft共识算法（七）——如果follower/candidate宕机了</a></li><li class="chapter-item expanded "><a href="Raft13.html"><strong aria-hidden="true">4.14.</strong> Raft共识算法（八）——时间与可用性</a></li><li class="chapter-item expanded "><a href="Raft14.html"><strong aria-hidden="true">4.15.</strong> 成员变更</a></li><li class="chapter-item expanded "><a href="Raft15.html"><strong aria-hidden="true">4.16.</strong> 日志压缩</a></li><li class="chapter-item expanded "><a href="Raft16.html"><strong aria-hidden="true">4.17.</strong> 与Client的交互</a></li><li class="chapter-item expanded "><a href="Raft17.html"><strong aria-hidden="true">4.18.</strong> 实验时遇到的bug</a></li><li class="chapter-item expanded "><a href="Raft18.html"><strong aria-hidden="true">4.19.</strong> 总结</a></li></ol></li><li class="chapter-item expanded "><a href="Zookeeper.html"><strong aria-hidden="true">5.</strong> Zookeeper</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="linearizability1.html"><strong aria-hidden="true">5.1.</strong> 线性一致性（一）——基础概念</a></li><li class="chapter-item expanded "><a href="linearizability2.html"><strong aria-hidden="true">5.2.</strong> 线性一致性（二）——细究linearizability</a></li><li class="chapter-item expanded "><a href="zk_intro.html"><strong aria-hidden="true">5.3.</strong> 引言</a></li><li class="chapter-item expanded "><a href="zk_service.html"><strong aria-hidden="true">5.4.</strong> Zookeeper Service</a></li><li class="chapter-item expanded "><a href="zk_api.html"><strong aria-hidden="true">5.5.</strong> Zookeeper API</a></li><li class="chapter-item expanded "><a href="zk_prop.html"><strong aria-hidden="true">5.6.</strong> Zookeeper的性质</a></li><li class="chapter-item expanded "><a href="zk_ex.html"><strong aria-hidden="true">5.7.</strong> 基于Zookeeper实现锁</a></li></ol></li><li class="chapter-item expanded "><a href="CRAQ.html"><strong aria-hidden="true">6.</strong> CRAQ</a></li><li class="chapter-item expanded "><a href="lamport_clock.html"><strong aria-hidden="true">7.</strong> Time, Clocks, and the Ordering of Events in a Distributed System</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="lamport_clock1.html"><strong aria-hidden="true">7.1.</strong> 引言</a></li><li class="chapter-item expanded "><a href="lamport_clock_partial_order.html"><strong aria-hidden="true">7.2.</strong> 偏序关系</a></li><li class="chapter-item expanded "><a href="lamport_logic_clock.html" class="active"><strong aria-hidden="true">7.3.</strong> 逻辑时钟</a></li><li class="chapter-item expanded "><a href="lamport_total_order.html"><strong aria-hidden="true">7.4.</strong> 全序关系</a></li><li class="chapter-item expanded "><a href="lamport_clock_ana_behave.html"><strong aria-hidden="true">7.5.</strong> 异常事件</a></li><li class="chapter-item expanded "><a href="lamport_p_clock.html"><strong aria-hidden="true">7.6.</strong> 物理时钟</a></li><li class="chapter-item expanded "><a href="lamport_end.html"><strong aria-hidden="true">7.7.</strong> 结论</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">6.828 操作系统</li><li class="chapter-item expanded "><a href="828intro.html"><strong aria-hidden="true">8.</strong> Killer of Microseconds</a></li><li class="chapter-item expanded "><a href="cloudlab.html"><strong aria-hidden="true">9.</strong> CloudLab</a></li><li class="chapter-item expanded "><a href="dpdk.html"><strong aria-hidden="true">10.</strong> DPDK</a></li><li class="chapter-item expanded "><a href="spdk.html"><strong aria-hidden="true">11.</strong> SPDK</a></li><li class="chapter-item expanded "><a href="Shenango.html"><strong aria-hidden="true">12.</strong> Shenango</a></li><li class="chapter-item expanded "><a href="TritonSort.html"><strong aria-hidden="true">13.</strong> TritonSort</a></li><li class="chapter-item expanded "><a href="Profiling.html"><strong aria-hidden="true">14.</strong> Profiling a warehouse-scale computer</a></li><li class="chapter-item expanded affix "><li class="part-title">6.828 - Network</li><li class="chapter-item expanded affix "><li class="part-title">CS244 - Advanced Topics in Networking</li><li class="chapter-item expanded "><a href="DARPA_NET.html"><strong aria-hidden="true">15.</strong> The Design Philosophy of The DARPA Internet Protocols</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="DARPA_NET2.html"><strong aria-hidden="true">15.1.</strong> Second Level Goals</a></li><li class="chapter-item expanded "><a href="DARPA_NET3.html"><strong aria-hidden="true">15.2.</strong> Types of Service</a></li><li class="chapter-item expanded "><a href="DARPA_NET4.html"><strong aria-hidden="true">15.3.</strong> Varieties of Networks</a></li><li class="chapter-item expanded "><a href="DARPA_NET5.html"><strong aria-hidden="true">15.4.</strong> Architecture and Implementation</a></li><li class="chapter-item expanded "><a href="DARPA_NET6.html"><strong aria-hidden="true">15.5.</strong> Datagrams</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">最后</li><li class="chapter-item expanded "><a href="end.html"><strong aria-hidden="true">16.</strong> 最后</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">读论文</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="逻辑时钟"><a class="header" href="#逻辑时钟">逻辑时钟</a></h1>
<p>接下来我们给系统引入时钟的概念。<br />
首先，从一个抽象的角度来看，时钟只是一种给事件分配一个数字的方式，这个数字是该事件发生的时间点。<br />
准确地，我们给每个进程\(P_i \)定义一个时钟\(C_i\)，这个时钟给进程中的任意一个事件\(a\)分配一个值\(C_i\langle a\rangle \)。<br />
整个系统的所有时钟用\(C \)来表示，它可以给任意一个事件\(b\)分配数字\(C\langle b\rangle \)。 若\(b\)是属于进程\(P_j \)的一个事件，则有\(C\langle b\rangle =C_j\langle b\rangle \)。<br />
目前来说，我们并不假设\(C_i\langle a\rangle \)的值与物理时间有关，所以我们把时钟\(C_i \)看作是一个逻辑上的时钟，而非物理上的时钟。<br />
这种逻辑时钟可以只使用计数器实现，不需要计时器的参与。</p>
<p>现在考虑这种定义是否能够让系统的逻辑时钟具有正确性。<br />
我们不能把该定义的正确性依托于物理时间，因为这需要时钟与物理时间保持同步。<br />
因此我们的定义必须依赖于事件发生的先后顺序。<br />
一个极强的合理的条件是：假设事件\(a\)先于事件\(b\)发生，那么\(a\)发生的时间点一定早于b。下文中，我们给出这个条件的严格定义。</p>
<blockquote>
<p><strong>Clock Condition</strong>:<br />
对于任意两个事件\(a\),\(b\),
若\(a\rightarrow b \)，则有\(C\langle a\rangle &lt; C\langle b\rangle \).</p>
</blockquote>
<p align="center"><img src="./assets/lamport_clock_f1.png" width="70%"></p>
<p>注意，这个条件的反命题是若\(a \nrightarrow b \)，则\(C\langle a\rangle =C\langle b\rangle \)。<br />
该反命题并不成立。因为这意味着两个并发的事件发生在同一时间。<br />
在图1中，\(p2\)和\(p3\)这两个事件，和\(q3 \)的关系都是并发执行的，如果反命题成立，则意味着\(p2\)、\(p3\)和\(q3 \)发生在同一时间。<br />
但是根据<strong>Clock Condition</strong>，有\(p2\rightarrow p3 \)，和该反命题矛盾。</p>
<p>从关系“\(\rightarrow \)”的定义出发，不难推导出，如果如下两个条件成立，则<strong>Clock Condition</strong>必成立。</p>
<ul>
<li><strong>C1</strong>. 如果a和b同属于进程\(P_i \)，并且a发生在b之前，则\(C_i\langle a \rangle &lt;C_i\langle b\rangle \)。</li>
<li><strong>C2</strong>. 如果a是进程\(P_i \)发送消息的事件，b是进程\(P_j \)接收该消息的事件，则\(C_i\langle a \rangle &lt; C_j\langle b\rangle \)。</li>
</ul>
<p>让我们通过程序时空图来进一步讨论时钟。假设一个进程的时钟每次都&quot;ticks&quot;所有数字，即每次事件发生的间隔中，时钟都在&quot;ticks&quot;。<br />
举个例子来说，如果a和b是进程\(P_i \)里连续发生的两个事件，\(C_i \langle a\rangle =4 \)，\(C_i\langle b\rangle =7 \)，那么在这两个事件的间隔中，时钟就滴答了5、6、7。</p>
<p align="center"><img src="./assets/lamport_clock_f2.png" width="70%"></p>
<p>We draw a dashed &quot;tick line&quot; through all the like-numbered ticks of the different processes.<br />
我们可以给这些不同的进程画上“tick line”。给图1画上“tick line”的结果如图2所示。</p>
<p><strong>条件C1</strong>意味着，同一进程中，位于相同进程时间线的任意两个事件之间必须有一条tick line。<br />
<strong>条件C2</strong>意味着，消息传递的波浪线必须穿过一条tick line。<br />
在图2中，箭头是有具体含义的，它代表了happens before的关系，不难看出，如果<strong>C1</strong>、<strong>C2</strong>这两个条件满足，则<strong>Clock Condition</strong>必满足。</p>
<blockquote>
<p><strong>额外的话</strong>：<br />
我对这个tick line有点不太理解，lamport在论文里并没有给出tick line的严格定义。上网搜别的资料，对这个tick line也没有过多的解释。<br />
我猜是说连接递增这个计数器的时刻，比如把所有set ticks=1的时刻用虚线连接起来，就是一条tick line。<br />
如果\(a\rightarrow b\)，那么从a到b的路线至少穿过一条tick line。）</p>
</blockquote>
<p align="center"><img src="./assets/lamport_clock_f3.png" width="70%"></p>
<p>接下来，我们可以使用笛卡尔坐标系来重新画这个tick line。把这些tick line抻直，我们就有了图3.<br />
图3是图2的另一种等价形式，都表示了系统中事件发生的次序。<br />
Without introducing the concept of physical time into the system (which requires introducing physical clocks), there is no way to decide which of these pictures is a better representation.</p>
<p>敏锐的读者应该发现，如果把网络中的进程在二维空间可视化出来，我们就有了一个三维的程序时空图。进程和消息仍然可以用线来表示，tick line则变成了二维的平面或曲面。</p>
<p>假设进程是计算机里的算法，事件则表示算法执行的具体过程。我们就可以在满足Clock Condition的情况下，引入时钟的概念了。<br />
进程\(P_i \)的时钟用寄存器\(C_i \)表示。那么\(C_i\langle a\rangle \)就是事件a发生的过程中，\(C_i
\)的值。<br />
在事件与事件的间隔中，\(C_i
\)的值也会发生改变，因此改变\(C_i
\)这一行为本身并不能看作是一个事件。</p>
<p>为了确保系统的时钟能够满足<strong>Clock Condition</strong>，我们需要确保该时钟可以满足<strong>条件C1</strong>和<strong>条件C2</strong>.
<strong>条件C1</strong>很好满足，进程只需要确保它遵守如下规则：</p>
<ul>
<li><strong>IR1</strong>. 每一个进程\(P_i \)在两个连续的事件间隔中，都需要递增\(C_i \)的值。</li>
</ul>
<p>为了确保<strong>条件C2</strong>，我们需要消息m里包含一个时间戳\(T_m \)，\(T_m \)的值等于该消息发送的时间。当一个进程收到带时间戳\(T_m \)的消息后，它必须将它的时钟增大到一个比\(T_m \)还要大的值。<br />
该规则的准确描述如下：</p>
<ul>
<li><strong>IR2</strong>. （a）如果事件a是进程\(P_i \)发送消息m的事件，则m必须包含一个时间戳\(T_m=C_i\langle a\rangle \)。<br />
(b) 当收到一个消息m的时候，进程\(P_j \)需要修改寄存器\(C_j \)的值，使该值大于等于当前\(C_j \)的值，并且还要大于\(T_m \)。</li>
</ul>
<p>在<strong>IR2.</strong> (b)中，我们认为接收消息m的事件发生在修改寄存器\(C_j \)之后。（这是为了数学形式上的好看，与具体实现无关）。</p>
<p>显然，<strong>IR2</strong>确保了<strong>条件C2</strong>可以被满足。因此，只要确保IR1和IR2，则Clock Condition必能满足，于是我们就有了给系统用的逻辑时钟，且该时钟是能够保证正确性的。</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="lamport_clock_partial_order.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="lamport_total_order.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="lamport_clock_partial_order.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="lamport_total_order.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
